﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Roles.Commands.Update;

/// <summary>
/// 校验修改角色信息
/// </summary>
public class UpdateRoleStatusCommandValidator : AbstractValidator<UpdateRoleStatusCommand>
{
    private readonly IApplicationDbContext _context;
    public UpdateRoleStatusCommandValidator(IApplicationDbContext context)
    {
        _context = context;
        RuleFor(v => v.RoleId)
            .MustAsync(RoleExistsAsync).WithMessage($"数据不存在！");

        RuleFor(v => v.RoleId)
           .MustAsync(AllowedUpdateRoleAsync).WithMessage($"禁止修改！");
    }

    /// <summary>
    /// 检查数据是否存在
    /// </summary>
    /// <param name="command"></param>
    /// <param name="roleId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> RoleExistsAsync(UpdateRoleStatusCommand command, long roleId, CancellationToken cancellationToken)
    {
        return await _context.Roles.AnyAsync(x => x.Id == roleId && x.ConcurrencyStamp == command.ConcurrencyStamp);
    }

    /// <summary>
    /// 禁止修改
    /// </summary>
    /// <param name="roleId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> AllowedUpdateRoleAsync(long roleId, CancellationToken cancellationToken)
    {
        var existingRole = await _context.Roles.SingleOrDefaultAsync(x => x.Id == roleId);

        if (existingRole == null)
        {
            return false;
        }
        if (string.Equals(existingRole.RoleCode, "admin", StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }
        return true;
    }
}